package com.qlk.odcinterface.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.qlk.odcinterface.domain.PmsProductPromotion;
import com.qlk.odcinterface.domain.PmsProductPromotionChannel;
import com.qlk.odcinterface.domain.PmsProductPromotionItem;
import com.qlk.odcinterface.domain.query.PmsProductPromotionQuery;
import com.qlk.odcinterface.manager.PmsProductPromotionManager;
import com.qlk.odcinterface.sdk.api.request.PmsProductPromotionRequest;
import com.qlk.odcinterface.service.PmsProductPromotionService;
import com.qlk.odcinterface.utils.bean.BeanUtilsEx;
import com.qlk.odcinterface.utils.exceptions.ExistedException;
import com.qlk.common.utils.page.PageUtil;
import com.qlk.common.utils.wrap.WrapMapper;
import com.qlk.common.utils.wrap.Wrapper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.perf4j.aop.Profiled;
 
/**
 * PmsProductPromotionService接口的实现类
 * 
 * @author zhaoyanan
 * @version 2016-4-14 13:22:58
 * 
 */
@Service
public class PmsProductPromotionServiceImpl implements PmsProductPromotionService {

    /** LOG */
    private static final Log LOG = LogFactory.getLog(PmsProductPromotionServiceImpl.class);

    @Autowired
    private PmsProductPromotionManager pmsProductPromotionManager;

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsProductPromotionService.batchInsert")
    public boolean insert(List<PmsProductPromotion> pmsProductPromotionList) {
        boolean resultFlag = false;
        try {
            if (CollectionUtils.isNotEmpty(pmsProductPromotionList)) {
                resultFlag = pmsProductPromotionManager.insert(pmsProductPromotionList);
            } else {
                LOG.warn("PmsProductPromotionServiceImpl#batchInsert failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#batchInsert has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsProductPromotionService.insert")
    public boolean insert(PmsProductPromotion pmsProductPromotion) {
        boolean resultFlag = false;
        try {
            if (null != pmsProductPromotion) {
                if (pmsProductPromotionManager.exist(pmsProductPromotion)) {
                    throw new ExistedException();
                }
                resultFlag = pmsProductPromotionManager.insert(pmsProductPromotion);
            } else {
                LOG.warn("PmsProductPromotionServiceImpl#insert failed, param is illegal.");
            }
        } catch (ExistedException e) {
            LOG.warn("PmsProductPromotionServiceImpl#insert failed, pmsProductPromotion has existed.");
            throw e;
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#insert has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsProductPromotionService.update")
    public boolean update(PmsProductPromotion pmsProductPromotion) {
        boolean resultFlag = false;
        try {
            if (null != pmsProductPromotion && null != pmsProductPromotion.getId()) {
                resultFlag = pmsProductPromotionManager.update(pmsProductPromotion);
            } else {
                LOG.warn("PmsProductPromotionServiceImpl#update failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#update has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsProductPromotionService.queryPmsProductPromotionList")
    public List<PmsProductPromotion> queryPmsProductPromotionList(PmsProductPromotionQuery queryBean) {
        List<PmsProductPromotion> pmsProductPromotionList = null;
        try {
            pmsProductPromotionList = pmsProductPromotionManager.queryPmsProductPromotionList(queryBean);
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#queryPmsProductPromotionList has error.", e);
        }
        return pmsProductPromotionList;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsProductPromotionService.queryPmsProductPromotionListWithPage")
    public List<PmsProductPromotion> queryPmsProductPromotionListWithPage(PmsProductPromotionQuery queryBean, PageUtil pageUtil) {
        List<PmsProductPromotion> pmsProductPromotionList = null;
        try {
            pmsProductPromotionList = pmsProductPromotionManager.queryPmsProductPromotionListWithPage(queryBean, pageUtil);
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#queryPmsProductPromotionListWithPage has error.", e);
        }
        return pmsProductPromotionList;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsProductPromotionService.delete")
    public boolean delete(PmsProductPromotion pmsProductPromotion) {
        boolean resultFlag = false;
        try {
            if (null != pmsProductPromotion && null != pmsProductPromotion.getId()) {
                resultFlag = pmsProductPromotionManager.delete(pmsProductPromotion);
            } else {
                LOG.warn("PmsProductPromotionServiceImpl#delete param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#delete has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsProductPromotionService.batchDelete")
    public boolean delete(PmsProductPromotion[] pmsProductPromotions) {
        boolean resultFlag = false;
        try {
            if (null != pmsProductPromotions && pmsProductPromotions.length > 0) {
                resultFlag = pmsProductPromotionManager.delete(pmsProductPromotions);
            } else {
                LOG.warn("PmsProductPromotionServiceImpl#batchDelete failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#batchDelete has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsProductPromotionService.getPmsProductPromotionById")
    public PmsProductPromotion getPmsProductPromotionById(Integer id) {
        PmsProductPromotion pmsProductPromotion = null;
        try {
            if (null != id) {
                pmsProductPromotion = pmsProductPromotionManager.getPmsProductPromotionById(id);
            } else {
                LOG.warn("PmsProductPromotionServiceImpl#getPmsProductPromotionById failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#getPmsProductPromotionById has error.", e);
        }
        return pmsProductPromotion;
    }
    
    @Profiled(tag = "PmsProductPromotionService.queryPmsProductPromotionList")
    public Wrapper<?> syncPmsProductPromotion(PmsProductPromotionRequest pmsProductPromotioRequest,int isStatusUpdate,String preStatus) {
        boolean resultFlag = false;
        String message = "";
        try {
            if (null != pmsProductPromotioRequest && null != pmsProductPromotioRequest.getId()) {
            	//处理请求中的参数，解析出单品促销表数据
            	PmsProductPromotion pmsProductPromotion = new PmsProductPromotion();
            	BeanUtils.copyProperties(pmsProductPromotioRequest,pmsProductPromotion);
            	//处理请求中的参数，解析出促销渠道对应表数据
            	List<PmsProductPromotionChannel> pmsProductPromotionChannelList = convertChannel(pmsProductPromotioRequest);        	 
            	
            	//处理请求中的参数，解析出单品促销明细表数据
            	List<PmsProductPromotionItem> pmsProductPromotionItemList = pmsProductPromotioRequest.getPromotionItemList();
            	
            	//1通过pms的单品促销表的促销活动编码，查询odc的单品促销表，如果不存在则插入，否则修改
                PmsProductPromotionQuery queryBean = new PmsProductPromotionQuery();
                queryBean.setId(pmsProductPromotion.getId());
                if(StringUtils.isNotBlank(preStatus) && !"0".equals(preStatus)){
                	queryBean.setStatus(Integer.parseInt(preStatus));
                }
                List<PmsProductPromotion> pmsList = pmsProductPromotionManager.queryPmsProductPromotionList(queryBean);
                //2存在，修改（通过标识判断是只修改单品促销表的数据状态还是促销表和明细表都修改）
                if(pmsList != null && pmsList.size() > 0){                     	        	    
        	      //2.1修改促销表状态
                	if(isStatusUpdate == 1){
                		PmsProductPromotion updatepmsProductPromotion = new PmsProductPromotion();
                		updatepmsProductPromotion.setId(pmsProductPromotion.getId());
                		updatepmsProductPromotion.setStatus(pmsProductPromotion.getStatus());
                		resultFlag = pmsProductPromotionManager.updatePmsProductPromotionStatus(pmsProductPromotion);
                		if(resultFlag){
                			message = "修改促销表状态成功";
                		}else{
                			message = "修改促销表状态成功失败";
                		}
                		//2.2删除促销表数据yn=0，明细表不做操作
                	}else if(isStatusUpdate == 2){
                		resultFlag = pmsProductPromotionManager.delete(pmsProductPromotion);//通过id删除：添加删除日期
                		if(resultFlag){
                			message = "删除促销表成功";
                		}else{
                			message = "删除促销表错误";
                		}
                		//2.3修改促销表和促销渠道对应表和明细表
                	}else{
                		resultFlag = pmsProductPromotionManager.updatePmsProductPromotion(pmsProductPromotion,pmsProductPromotionChannelList,pmsProductPromotionItemList);                   		
                		if(resultFlag){
                			message = "修改促销表和促销渠道对应表和明细表成功";
                		}else{
                			message = "前置状态错误修改促销表和促销渠道对应表和明细表失败";
                		}
                	}
                //1不存在，插入
                }else{
                	//1.2存在数据但是前置状态错误，导致查不到数据
                	if(StringUtils.isNotBlank(preStatus) && !"0".equals(preStatus)){
                		resultFlag = false;
                		message = "前置状态错误";
            		//1.1不存在数据
                	}else{
                		resultFlag = pmsProductPromotionManager.insertPmsProductPromotion(pmsProductPromotion,pmsProductPromotionChannelList,pmsProductPromotionItemList);            	               		
                		if(resultFlag){
                			message = "插入成功";
                		}else{
                			message = "插入失败";
                		}
                	}
                }		
               
            } else {
                LOG.warn("PmsProductPromotionServiceImpl#syncPmsProductPromotion failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsProductPromotionServiceImpl#syncPmsProductPromotion has error.", e);
        }
        if(resultFlag){
        	return WrapMapper.ok().message(message);       	
        }else{
        	return WrapMapper.error().message(message);         	
        }
    }
    public List<PmsProductPromotionChannel> convertChannel(PmsProductPromotionRequest pmsProductPromotioRequest){
    	List<PmsProductPromotionChannel> pmsProductPromotionChannelList = null;
    	String channels = pmsProductPromotioRequest.getChannel();
    	if(channels != null && !"".equals(channels)){
    		//10：大白云诊，20：七乐康PC网页，30：七乐康APP，40：七乐康微信端，50：七乐康WAP。多渠道之间以半角逗号作为分割
    		String[] channelArray = channels.split(",");
    		pmsProductPromotionChannelList = new ArrayList<PmsProductPromotionChannel>();
    		for(String channel : channelArray){
    			PmsProductPromotionChannel pmsProductPromotionChannel = new PmsProductPromotionChannel();
    			pmsProductPromotionChannel.setChannelId(Integer.parseInt(channel));
    			pmsProductPromotionChannel.setPromotionId(pmsProductPromotioRequest.getId());
    			pmsProductPromotionChannelList.add(pmsProductPromotionChannel);
    		}
    	}
    	return pmsProductPromotionChannelList;
    }
}

